package handler

import (
	"bike-vb/cache"
	"bike-vb/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func BigcarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	/*
		SELECT
		  big_car_orders.id AS OrderId,
		  big_cars.car_code AS CarCode,
		  big_cars.car_name AS CarName,
		  big_cars.car_price AS CarPrice,
		  big_car_orders.order_code AS OrderCode,
		  big_car_orders.order_price AS OrderPrice
		FROM
		  big_car_orders
		  LEFT JOIN big_cars ON big_cars.id = big_car_orders.cid
	*/
	var list []model.BigCarOrderList

	redis_key := "bigCar_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("big_car_orders").
			Select(
				"big_car_orders.id AS OrderId",
				"big_cars.car_code AS CarCode",
				"big_cars.car_name AS CarName",
				"big_cars.car_price AS CarPrice",
				"big_car_orders.order_code AS OrderCode",
				"big_car_orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN big_cars ON big_cars.id = big_car_orders.cid").
			Offset(offset).
			Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	model.DB.Model(&model.BigCarOrder{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取成功",
		"data":  list,
		"total": total,
	})

}

func BigcarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var detail model.CarOrderList

	redis_key := "bigCar_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("big_car_orders").
			Select(
				"big_car_orders.id AS OrderId",
				"big_cars.car_code AS CarCode",
				"big_cars.car_name AS CarName",
				"big_cars.car_price AS CarPrice",
				"big_car_orders.order_code AS OrderCode",
				"big_car_orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN big_cars ON big_cars.id = big_car_orders.cid").
			Where("big_car_orders.id = ?", id).
			Find(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &detail)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": detail,
	})
}
